package initialize

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"interview/models"
	"interview/pkg/global"
)

// Mysql 初始化MySQL
func Mysql() {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?%s",
		global.Conf.Mysql.Username,
		global.Conf.Mysql.Password,
		global.Conf.Mysql.Host,
		global.Conf.Mysql.Port,
		global.Conf.Mysql.Database,
		global.Conf.Mysql.Query,
	)
	gormConfig := gorm.Config{}
	if global.Conf.Mysql.LogMode {
		gormConfig.Logger = logger.Default.LogMode(logger.Info)
	}

	db, err := gorm.Open(mysql.Open(dsn), &gormConfig)
	if err != nil {
		global.Logger.Panicf("初始化MySQL异常：%v", err)
	}
	global.Db = db
	autoMigrate()
	global.Logger.Debug("初始化MySQL完毕")

	// 初始化数据库日志监听器
	initBinlog()
}

// 自动迁移表结构
func autoMigrate() {
	global.Db.AutoMigrate(
		new(models.User),
		new(models.Membership),
	)
}

func initBinlog() {
	MysqlBinlog([]string{
		new(models.User).TableName(),
		new(models.Membership).TableName(),
	})
}
